package pl.lodz.p.jobs;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import pl.lodz.p.beans.utils.HibernateUtil;
import pl.lodz.p.model.Doctor;
import pl.lodz.p.model.Notification;
import pl.lodz.p.services.NotificationSendService;
import pl.lodz.p.services.NotificationSendServiceImpl;
 
public class SchedulerJob implements Job {
 
	public void execute(JobExecutionContext context) throws JobExecutionException {
		List<Notification> allToSend = findAll();
		NotificationSendService service = new NotificationSendServiceImpl();

		for (Notification notification : allToSend) {
			if (notification.getCanal().isSms()){
				service.sendSms("Przypominamy o wizycie dnia " + notification.getVisit().getDateStart() 
						+ " u doktora " + notification.getVisit().getSchedule().getDoctor().getFirstName() 
						+ notification.getVisit().getSchedule().getDoctor().getLastName()
						, "660874861");
				System.out.println("Email: Przypominamy o wizycie dnia " + notification.getVisit().getDateStart() 
						+ " u doktora " + notification.getVisit().getSchedule().getDoctor().getFirstName() 
						+ notification.getVisit().getSchedule().getDoctor().getLastName());
			}
			if (!notification.getCanal().isSms()){
				service.getSendEmail("grzegorzwyrwas10@gmail.com", "Wizyta", 
						"Przypominamy o wizycie dnia " + notification.getVisit().getDateStart() + " u doktora " 
							+ notification.getVisit().getSchedule().getDoctor().getFirstName()
							+ notification.getVisit().getSchedule().getDoctor().getLastName());
				System.out.println("SMS: Przypominamy o wizycie dnia " + notification.getVisit().getDateStart() + " u doktora " 
							+ notification.getVisit().getSchedule().getDoctor().getFirstName()
							+ notification.getVisit().getSchedule().getDoctor().getLastName());
			}
			
		}
		deleteAll();
	}
	
	public List<Notification> findAll() {
		List<Notification> res = new ArrayList<Notification>();
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			res = session.createQuery("from Notification where date < :to").setParameter("to", new Date()).list();
			return res;
		} catch (Exception e) {
				e.printStackTrace();
		} finally {
			session.close();
		}
		return null;
	}
	
	public void deleteAll(){
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			String stringQuery = "DELETE FROM Notification WHERE date < :to";
			Query query = session.createQuery(stringQuery).setParameter("to", new Date());
			query.executeUpdate();
		} catch (Exception e) {
				e.printStackTrace();
		} finally {
			session.close();
		}
	}
}